module.exports = function (app, models, $, db, nm) {
	//获取用户列表
	app.get('/v1/member', (req, res) => {
		var query = {
			pageSize: req.query.pageSize || 10,
			pageNum: req.query.pageNum || 1,
			unitId: req.unitId
		}
		if (req.query.openId) query.openId = { $regex: req.query.openId }
		if (req.query.name) query.name = { $regex: req.query.name }
		models.member.list(query, ret => {
			res.send(ret)
		}, {
			projection: {
        openId: 1,
				name: 1,
				gender: 1,
        avatarUrl: 1,
				phone: 1,
        nickName: 1,
				IDCard: 1,
				address: 1,
				grade: 1,
        userId: 1,
        recomendName: 1,
        recomend: 1,
				_id: 1,
			}
		})
	})
	//获取用户详情
	app.get('/v1/memberInfo',(req,res) => {
		if(req.query._id){
			models.member.find({_id:req.query._id}, ret => {
				res.send(ret)
			})
		}else{
			res.send({errorMsg:'请传入_id'})
		}
	})
	//新增用户信息
	app.post('/v1/member',(req,res) => {
		req.body.unitId = req.unitId
		models.member.insert(req.body, ret => {
			res.send(ret)
		})
	})
	//修改用户信息
	app.put('/v1/member',(req,res) => {
        req.body.openId = undefined
		models.member.update({ _id:req.body._id },req.body, ret => {
			res.send(ret)
		})
	})
  //会员登录
  function memberLogin(member,res){
    var memberInfo = member;
    memberInfo.id = member._id;
    models.session.insert({
      id:member.session_key,
      unitId: member.unitId,
      userId: member._id,
      userName: member.openId,
      platform: 'WeChatMiniApp',
      type: 2,
      inTime: $.date(new Date()).Format('yyyy-MM-dd hh:mm:ss')
    }, function(ret) {
      if (!ret.errorMsg) {
        memberInfo.token = ret.id;
        res.send(memberInfo);
      } else {
        res.send(ret);
      }
    })
  }
  //code换取openId
  app.get('/wxlogin',function(req,res){
    if(req.query.code && req.query.appid && req.query.secret && req.query.unitId){
		new $.Tencent({appid:req.query.appid,secret:req.query.secret}).auth.code2Session(req.query.code,function(ret){
        if(!ret.errorMsg){
          models.member.find({ openId:ret.openid },function(memberRet){
            if (!memberRet._id) {
              models.member.insert({
                openId:ret.openid,
                unitId:req.query.unitId
              },function(memberRet){
                if(!memberRet.errorMsg){
                  memberRet.openId = ret.openid;
                  memberRet.session_key = ret.session_key;
                  memberLogin(memberRet,res);
                }else{
                  res.send(memberRet);
                }
              })
            }else{
              memberRet.session_key = ret.session_key;
              memberLogin(memberRet,res);
            }
          })
        }else{
          res.send(ret);
        }
      })
    }else{
      res.send({errorMsg:'请传入code,appid,secret,unitId'});
    }
  })
}